package com.xjw.hospital.utils;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xjw.coreutil.cache.CacheUtil;
import com.xjw.coreutil.common.PropUtil;
import com.xjw.coreutil.common.StringUtil;
import com.xjw.hospital.entity.DocInfo;

import java.io.File;
import java.util.Arrays;
import java.util.List;

/**
 * @author 徐军文
 * @since 2022/8/10 12:32
 */
@SuppressWarnings("deprecation")
public class ToolUtil {

    private static String token = "";

    private static final String sysCode = "1001035";

    private static final int timeout = 3000;

    private static final Log LOGGER = LogFactory.get();

    public static PropUtil propUtil = PropUtil.getInstance(PropUtil.USERDATA);

    public static void setToken(String tokenStr) {
        if (!StringUtil.isEmpty(tokenStr) && !tokenStr.equals(token)) {
            token = tokenStr;
        }
    }

    public static String getToken() {
        return token;
    }

    public static String getPhsSign() {
        String time = "1001035_" + System.currentTimeMillis();
        return SecureUtil.des("W7ZEgfnv".getBytes()).encryptBase64(time);
    }

    public static void main(String[] args) {
        System.out.println(getPhsSign());
    }

    public static void getTicket(DocInfo docInfo, int timeout) {
        Thread thread = CacheUtil.get(docInfo.getDocId());
        if (thread != null)  {
            return;
        }
        thread = new Thread(() -> {
            while(true) {
                getTicket(docInfo.getDocInfoJson());
                ThreadUtil.sleep(timeout);
            }
        });
        thread.start();
        CacheUtil.put(docInfo.getDocId(), thread);
    }

    public static void getTicket(JSONObject doc) {
        List<String> msgCache = CacheUtil.get("msgCache");
        try {
            JSONObject param = getDocSch(doc);
            getNumberSource(param);
            getPatCardList(param);
            String msg = addReg(param);
            msgCache.add(msg);
            sendEmail(msg);
            Thread thread = CacheUtil.get(doc.getString("docId"));
            msgCache.add(doc.getString("docName") + "抢票成功");
            thread.stop();
            CacheUtil.remove(doc.getString("docId"));
        } catch (RuntimeException e) {
            if (StringUtil.isEmpty(e.getMessage())) {
                msgCache.add("抢票空指针异常");
            } else {
                msgCache.add(e.getMessage());
            }
        } catch (Exception e) {
            LOGGER.error("fail to get ticket", e);
            msgCache.add(e.getMessage());
        }
    }

    public static void sendEmail(String content) {
        EmailUtil.sendEmail(content, getReceiver());
    }

    public static void stopGetTicket(DocInfo docInfo) {
        Thread thread = CacheUtil.get(docInfo.getDocId());
        List<String> msgCache = CacheUtil.get("msgCache");
        if (thread != null) {
            thread.stop();
            msgCache.add(docInfo.getDocName() + ":任务已停止");
            CacheUtil.remove(docInfo.getDocId());
            sendEmail("停止抢号--" + docInfo.getDocName());
        } else {
            msgCache.add(docInfo.getDocName() + ":没有任务运行");
        }
    }

    public static String getPng(String path) {
        String url = "http://wechat.jshtcm.com/cas-wechat/*.jsonRequest";
        String res = HttpRequest.post(url).timeout(timeout)
                .header("X-Service-Id", " cas-wechat.smsService")
                .header("X-Service-Method", "getVerifyCodeInfo")
                .header("phsId", "81681688").header("phsSign", getPhsSign())
                .body("[{}]")
                .execute().body();
        JSONObject body = JSON.parseObject(res).getJSONObject("body");
        String pngInfo = body.getString("verifyCode");
        Base64.decodeToFile(pngInfo, new File(path));
        return body.getString("uniqueId");
    }

    public static String login(String phone, String verrifyCode, String uniqueId) {
        String url = "http://wechat.jshtcm.com/cas-wechat/logon/login";
        String param = "{\n" +
                "  \"tenantId\": \"hcn.jsszyy\",\n" +
                "  \"pwd\": \"5d6476ad430db20b1715f2d82d491293\",\n" +
                "  \"forAccessToken\": true,\n" +
                "  \"rid\": \"patient\",\n" +
                "  \"verifyCode\": \"" + verrifyCode + "\",\n" +
                "  \"uniqueId\": \"" + uniqueId + "\",\n" +
                "  \"loginName\": \"" + phone + "\"\n" +
                "}";
        return HttpRequest.post(url).timeout(timeout).body(param).execute().body();
    }

    public static JSONObject getDocSch(JSONObject docInfo) {
        String url = "https://netphs.eheren.com/phs-reg/reg/getDocSch";
        String param = "{\"args\":{\n" +
                "  \"docId\": \""+docInfo.getString("docId")+"\",\n" +
                "  \"deptId\": \""+docInfo.getString("deptId")+"\",\n" +
                "  \"hosId\": \""+docInfo.getString("hosId")+"\",\n" +
                "  \"sysCode\": \""+sysCode+"\"\n" +
                "},\"token\":\"" + "" + "\"}";
        String res = HttpRequest.post(url).timeout(timeout)
                .header("phsId", "81681688").header("phsSign", getPhsSign())
                .body(param).execute().body();
        JSONArray dataList = JSON.parseObject(res).getJSONObject("result").getJSONArray("dataList");
        for (int i = 0;i < dataList.size();i++) {
            JSONArray schDateList = dataList.getJSONObject(i).getJSONArray("schDateList");
            for (int j = 0;j < schDateList.size();j++) {
                JSONObject data = schDateList.getJSONObject(j);
                if (data.getString("schState").equals("0")) {
                    data.put("resDate", dataList.getJSONObject(i).getString("schDate"));
                    return data;
                }
            }
        }
        throw new RuntimeException("没有号");
    }

    public static void getNumberSource(JSONObject data) {
        String url = "https://netphs.eheren.com/phs-reg/reg/getNumberSource";
        String param = "{\"args\":{\n" +
                "  \"sysCode\": \""+sysCode+"\",\n" +
                "  \"ampm\": \""+data.getString("ampm")+"\",\n" +
                "  \"categor\": \""+data.getString("categor")+"\",\n" +
                "  \"docId\": \""+data.getString("docId")+"\",\n" +
                "  \"deptId\": \""+data.getString("deptId")+"\",\n" +
                "  \"hosId\": \""+data.getString("hosId")+"\",\n" +
                "  \"schDate\": \""+data.getString("schDate")+"\",\n" +
                "  \"schId\": \""+data.getString("schId")+"\"\n" +
                "},\"token\":\""+token+"\"}";
        String res = HttpRequest.post(url).timeout(timeout)
                .header("phsId", "81681688").header("phsSign", getPhsSign())
                .body(param).execute().body();
        JSONArray result = JSON.parseObject(res).getJSONArray("result");
        for (int i = 0;i < result.size();i++) {
            JSONObject ticket = result.getJSONObject(i);
            if (Integer.parseInt(ticket.getString("disNo")) > 0) {
                data.put("timeDesc", ticket.getString("timeDesc"));
                data.put("disNo", ticket.getString("disNo"));
                return;
            }
        }
    }

    public static void getPatCardList(JSONObject data) {
        String url = "https://netphs.eheren.com/phs-base/relevantPatient/getPatCardList";
        String param = "{\"args\":{\n" +
                "  \"sysCode\": \""+sysCode+"\"\n" +
                "},\"token\":\""+token+"\"}";
        String res = HttpRequest.post(url).timeout(timeout)
                .header("phsId", "81681688").header("phsSign", getPhsSign())
                .body(param).execute().body();
        JSONArray result = JSON.parseObject(res).getJSONArray("result");
        String patienId = result.getJSONObject(0).getString("patienId");
        data.put("patienId", patienId);
    }

    public static String addReg(JSONObject data) {
        String url = "https://netphs.eheren.com/phs-reg/reg/addReg";
        String param = "{\"args\":{\n" +
                "  \"clinicalType\": \""+data.getString("clinicalType")+"\",\n" +
                "  \"visitingArea\": \"\",\n" +
                "  \"ampm\": \""+data.getString("ampm")+"\",\n" +
                "  \"appointmentNumber\": \"3\",\n" +
                "  \"categor\": \""+data.getString("categor")+"\",\n" +
                "  \"categorName\": \""+data.getString("categorName")+"\",\n" +
                "  \"deptId\": \""+data.getString("deptId")+"\",\n" +
                "  \"deptName\": \""+data.getString("deptName")+"\",\n" +
                "  \"docId\": \""+data.getString("docId")+"\",\n" +
                "  \"disNo\": \""+data.getString("disNo")+"\",\n" +
                "  \"docName\": \""+data.getString("docName")+"\",\n" +
                "  \"endTime\": \"\",\n" +
                "  \"extend\": \"\",\n" +
                "  \"fee\": \""+data.getString("fee")+"\",\n" +
                "  \"hosId\": \""+data.getString("hosId")+"\",\n" +
                "  \"hosName\": \""+data.getString("hosName")+"\",\n" +
                "  \"isFlexible\": \"\",\n" +
                "  \"numId\": \"\",\n" +
                "  \"patientId\": \""+data.getString("patienId")+"\",\n" +
                "  \"resDate\": \""+data.getString("resDate")+"\",\n" +
                "  \"schId\": \""+data.getString("schId")+"\",\n" +
                "  \"source\": 22,\n" +
                "  \"startTime\": \"\",\n" +
                "  \"sysCode\": \""+sysCode+"\",\n" +
                "  \"thirdUserId\": \"\",\n" +
                "  \"timeDesc\": \""+data.getString("timeDesc")+"\",\n" +
                "  \"timePoint\": \"\",\n" +
                "  \"schQukCategor\": \""+data.getString("schQukCategor")+"\"\n" +
                "},\"token\":\""+token+"\"}";
        String res = HttpRequest.post(url).timeout(timeout)
                .header("phsId", "81681688").header("phsSign", getPhsSign())
                .body(param).execute().body();
        JSONObject resJson = JSON.parseObject(res);
        if (StringUtil.isEmpty(resJson.getString("result"))) {
            return resJson.getString("message");
        } else {
            return resJson.getJSONObject("result").getString("hint");
        }
    }

    public static JSONArray searchDoc(String name) {
        String url = "https://netphs.eheren.com/phs-reg/regDoc/searchDocAndDeptByWords";
        String param = "{\n" +
                "    \"args\": {\n" +
                "        \"clinicalType\": \"1\",\n" +
                "        \"hosId\": \"12675\",\n" +
                "        \"searchContent\": \""+name+"\",\n" +
                "        \"sysCode\": \"1001035\"\n" +
                "    },\n" +
                "    \"token\": \""+""+"\"\n" +
                "}";
        String res = HttpRequest.post(url).body(param).timeout(timeout)
                .header("phsId", "81681688").header("phsSign", getPhsSign())
                .execute().body();
        return JSON.parseObject(res).getJSONObject("result").getJSONArray("docInfoResultList");
    }

    public static String getReceiver() {
        if (StringUtil.isNotEmpty(propUtil.getStr("receiver"))) {
            return propUtil.getStr("receiver");
        } else {
            return "18355093023@163.com";
        }
    }

}
